﻿using ManageReportVer1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ManageReportVer1.Controllers
{
    [Authorize(Roles = "Admin")]
    public class RoleController : Controller
    {
        //
        // GET: /Role/

        //Add Role
        public ActionResult AddRole()
        {
            RoleModel role = new RoleModel();
            return View(role);
        }

        [HttpPost]
        public ActionResult AddRole(RoleModel role)
        {
            DBDataContext context = new DBDataContext();
            if (ModelState.IsValid)
            {
                Role roles = new Role();
                roles.RoleName = role.RoleName;
                roles.Description = role.Description;

                context.Roles.InsertOnSubmit(roles);
                context.SubmitChanges();
                return RedirectToAction("ViewRole", "Role");
            }
            return View(role);
        }

        //View Role
        public ActionResult ViewRole()
        {
            DBDataContext context = new DBDataContext();
            var role = from s in context.Roles orderby s.RoleId ascending select s;
            return View(role.ToList());
        }

        //Update Role
        [HttpGet]
        public ActionResult UpdateRole(string id)
        {
            int roleId = Convert.ToInt32(id);
            DBDataContext context = new DBDataContext();
            Role role = context.Roles.Single(n => n.RoleId == roleId);
            return View(role);
        }

        [HttpPost]
        public ActionResult UpdateRole(Role role)
        {
            DBDataContext context = new DBDataContext();
            if (ModelState.IsValid)
            {
                Role roleUpdate= context.Roles.Single(s => s.RoleId == role.RoleId);
                roleUpdate.RoleName = role.RoleName;
                roleUpdate.Description = role.Description;

                context.SubmitChanges();
                return RedirectToAction("ViewRole", "Role");
            }
            return View(role);
        }

        //Delete Department
        public ActionResult DeleteRole(string id)
        {
            int roleId = Convert.ToInt32(id);
            DBDataContext context = new DBDataContext();
            Role role = context.Roles.Single(n => n.RoleId == roleId);
            context.Roles.DeleteOnSubmit(role);
            context.SubmitChanges();
            return RedirectToAction("ViewRole", "Role");
        }

    }
}
